package com.jms.fu.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.jms.fu.exception.DAOException;
import com.jms.fu.model.bean.App;
import com.jms.fu.model.bean.User;
import com.jms.fu.model.bo.AppBO;
import com.jms.fu.model.bo.AppDownBO;
import com.jms.fu.model.bo.TransactionBO;
import com.jms.fu.model.bo.UserBO;

public class CheckOutAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession();
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
			return mapping.findForward("failed");
		}
		if (session.getAttribute("cart") == null
				|| session.getAttribute("username") == null) {
			out.print("login");
			return null;
		}
		String role = (String) session.getAttribute("role");
		String username = (String) session.getAttribute("username");
		ArrayList<Integer> listApp = (ArrayList<Integer>) session
				.getAttribute("cart");
		ArrayList<String> listLink = new ArrayList<String>();
		session.removeAttribute("cart");
		float total = 0;
		AppBO appbo = new AppBO();
		AppDownBO appdown = new AppDownBO();
		App app = new App();
		try {
			for (int temp : listApp) {

				app = appbo.getAppByID(temp);
				float price = app.getPrice();
				String appname = appbo.getNumberOfFile(
						getServlet().getServletContext().getRealPath("/")
								+ app.getLink()).get(0);
				listLink.add(app.getLink() + "/" + appname);
				if (price == 0 || appdown.checkAppOwnByUsername(username, temp)
						|| app.getDevId().equals(username)
						|| role.equals("Administrator")) {

				} else {
					total += price;
				}
			}
			UserBO userbo = new UserBO();
			User user = userbo.getUserInfoByUsername(username);

			if (user.getBalance() < total) {
				out.print("charge");
				return null;
			} else {
				for (int temp : listApp) {
					app = appbo.getAppByID(temp);
					float price = app.getPrice();
					TransactionBO tbo = new TransactionBO();

					if (price == 0
							|| appdown.checkAppOwnByUsername(username, temp)
							|| app.getDevId().equals(username)
							|| role.equals("Administrator")) {
						if (!appdown.checkAppOwnByUsername(username, temp)
								&& !app.getDevId().equals(username)
								&& !role.equals("Administrator")) {
							app.setNumberOfDownload(app.getNumberOfDownload() + 1);
							appbo.updateFullApp(app);
							appdown.addAppToUsername(username, temp,
									app.getUpVersion());
						}
					} else {

						userbo.deposit(username, user.getBalance() - price);
						userbo.deposit(app.getDevId(), userbo
								.getUserInfoByUsername(app.getDevId())
								.getBalance()
								+ price);
						appdown.addAppToUsername(username, temp,
								app.getUpVersion());
						if (!appdown.checkAppOwnByUsername(username, temp)
								&& !app.getDevId().equals(username)
								&& !role.equals("Administrator")) {
							app.setNumberOfDownload(app.getNumberOfDownload() + 1);
							appbo.updateFullApp(app);
						}
						tbo.addNewTransaction(username, temp, price, 0, 0);
					}

					String appname = appbo.getNumberOfFile(
							getServlet().getServletContext().getRealPath("/")
									+ app.getLink()).get(0);
				}

				String applistHTML = "";
				int i = 0;
				for (int appid : listApp) {
					app = appbo.getAppByID(appid);
					ArrayList<String> avatar = appbo
							.getNumberOfFile(getServlet().getServletContext()
									.getRealPath("/")
									+ app.getLink()
									+ "/Avatar");
					String avatarLink;
					if (avatar.size() == 0) {
						avatarLink = "references/images/avatar.jpg";
					} else {
						avatarLink = app.getLink() + "/Avatar/" + avatar.get(0);
					}
					applistHTML += "<li class='list-group-item'> "
							+ " <div class='col-xs-12 col-sm-3'> <img src='"
							+ avatarLink
							+ "'style='width: 50px;height: 50px;'> </div>"
							+ "<a class='item-g' href='getAppDetail.jms?appid="
							+ app.getAppId() + "'>" + app.getAppName()
							+ "</a> </div>" + "<a class='item-g' href='"
							+ listLink.get(i) + "'> Download </a>"
							+ " <div class='clearfix'></div></li>";
					i++;
				}
				out.print(applistHTML);
			}
		} catch (DAOException e) {
			e.printStackTrace();
		}
		return null;
	}

}
